<?php

class c5_client{

	var $parameters = array();
	var $remote_user_id = "" ;
	var $salt = "" ;
	var $timeout = 3 ;
	var $debug = false ;

	function get_verify_code(){
		$string = $this->salt ;
		while (list($key, $val) = each($this->parameters)) {
			$string .= $key ;
			$string .= $val ;
		}
		$string .= $this->salt ;
		return md5($string);
	}
	
	function call($url){
		$this->init();
		$this->debug(http_build_query($this->parameters)) ;
		$options = array(
			'http' => array(
				'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
				'method'  => 'POST',
				'content' => http_build_query($this->parameters),
				'timeout' => $this->timeout 
			)
		);
		$context  = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		$object = json_decode($result,true);

		return $object;
	}

	function init(){
		$args = $this->parameters ;
		$ignores = array("salt"=>1,"remote_verify_code"=>1);
		$args = array_diff_key($args, $ignores);
		$args["remote_user_id"] = $this->remote_user_id ;
		$args["timestamp"] = $this->get_milli_time() ;
		ksort($args);
		$this->parameters = $args ;
		$this->parameters["remote_verify_code"] = $this->get_verify_code() ;
		$this->parameters["salt"] = "" ;
	}

	function get_milli_time(){
		$time_test = microtime();
		list($ten_thousand,$sec) = explode(" ",$time_test);
		$time=((float)$ten_thousand+(float)$sec);
		return round($time*1000);
	}

	function debug($string){
		if($this->debug){
			print '<br>c5_client debug: ' . $string ;
		}
	}

	function add_parameter($name,$value){
		$this->parameters[$name] = $value ;
	}

	function set_salt($salt){
		$this->salt = $salt ;
	}

	function set_debug($debug){
		$this->debug = $debug ;
	}
	
	function set_remote_user_id($remote_user_id){
		$this->remote_user_id = $remote_user_id ;
	}

	function set_timeout($timeout){
		$this->timeout = $timeout ;
	}

	function add_parameters($parameters){
		$this->parameters = array_merge($this->parameters, $parameters) ;
	}
}
